package com.ultra.validator;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.ultra.constraint.Constraint;
import com.ultra.exception.UnableResolveTypeException;
import com.ultra.template.content.AcvContext;
import com.ultra.template.content.Argument;
import com.ultra.template.content.Pairs;
import com.ultra.template.parse.Parser;
import lombok.extern.slf4j.Slf4j;

import javax.script.ScriptException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

@Slf4j
public class Active {
    /**
     * 激活验证器
     *
     * @throws IllegalArgumentException 如果 arguments 为 null
     */
    public void activateValidator(Map<Pairs, Constraint> constraints) {
        try {
            // 收集参数信息 设置随机化模板 并对其进行扁平化处理
            List<Argument> arguments = Parser.parseMethodSignature();

            // 构造 对数器上下文
            AcvContext acvContext = new AcvContext(arguments);

            Constraint.preParseConstraint(acvContext,constraints);
            // 启动验证过程
            boolean result = verifyArguments(acvContext);
            // 记录验证结果日志
            if (result) {
                log.info("test passed!");
            } else {
                log.error("test failed!");
            }
        } catch (Exception e) {
            log.error("test failed,take exception!", e);
        }
    }


    private boolean verifyArguments(AcvContext context) throws JsonProcessingException, UnableResolveTypeException, ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException, ScriptException {
        return new Validator().verification(context);
    }
}
